package boun.swe.bob.service;

import boun.swe.bob.entities.*;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import boun.swe.bob.entities.Publication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * This controller is used for my friend requests page actions
 */
public class PublicationsController extends BaseController {

    /**
     * Shows the page
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return page
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();

        String wantedUserId = httpServletRequest.getParameter("wantedUserId");
        User wantedUser = null;

        if(null == wantedUserId) {
            wantedUser=userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId());
            myModel.put("user", wantedUser);
            myModel.put("himself",  true  );
            myModel.put("wantedUserId",getLoggedInUser(httpServletRequest).getUserId());
        } else {
            wantedUser=userDao.findByPrimaryKey(Integer.parseInt(wantedUserId));
            myModel.put("user", wantedUser);
            myModel.put("himself",  false  );
            myModel.put("wantedUserId",httpServletRequest.getParameter("wantedUserId"));
        }


        boolean isHeFriend = isHeFriend(getLoggedInUser(httpServletRequest), wantedUser);
        boolean friendshipApprovalWaiting = false;
        if(isHeFriend) {
            FriendsPK friendPK = new FriendsPK();
            friendPK.setUser1Id(getLoggedInUser(httpServletRequest).getUserId());
            friendPK.setUser2Id(Integer.parseInt(wantedUserId));
            Friend friend = friendDao.findByPrimaryKey(friendPK);
            if(null != friend)
                friendshipApprovalWaiting = friend.getApproved() == 0 ? true : false;
        }
        myModel.put("loggedInUser", getLoggedInUser(httpServletRequest));
        myModel.put("isHeFriend", isHeFriend);
        myModel.put("friendshipApprovalWaiting", friendshipApprovalWaiting);


        if(!Strings.isNullOrEmpty(wantedUserId))
        {
            myModel.put("publications",publicationDao.getPublicationsByUserId(Integer.parseInt(wantedUserId)));
            myModel.put("mode", "list");
            return new ModelAndView("publications", "model", myModel);
        }
        else
        {
            myModel.put("himself",  true  );

            String editId = httpServletRequest.getParameter("editId");
            String deleteId = httpServletRequest.getParameter("deleteId");

            //List publications
            if(Strings.isNullOrEmpty(editId) && Strings.isNullOrEmpty(deleteId))
            {
                wantedUserId=getLoggedInUser(httpServletRequest).getUserId().toString();
                myModel.put("publications",publicationDao.getPublicationsByUserId(Integer.parseInt(wantedUserId)));
                myModel.put("mode", "list");
                
                return new ModelAndView("publications", "model", myModel);
            }

            //New/Edit
            if(!Strings.isNullOrEmpty(editId))
            {
                //New publication
                if(editId.equals("-1"))
                {
                    Publication publication=new Publication();
                    publication.setPublicationId(-1);

                    myModel.put("publication", publication);
                    myModel.put("mode", "new");

                    return new ModelAndView("publications", "model", myModel);
                }
                else
                {
                    //Edit publication
                    Publication publication=publicationDao.getPublicationByPublicationId(Integer.parseInt(editId));

                    if(publication==null)
                    {
                        try {
                            httpServletResponse.sendRedirect("/bob-web/service/publications.htm");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    myModel.put("mode", "edit");
                    myModel.put("publication", publication);

                    return new ModelAndView("publications", "model", myModel);
                }
            }
            
            //Delete publication
            if(!Strings.isNullOrEmpty(deleteId))
            {
                Publication publication=publicationDao.getPublicationByPublicationId(Integer.parseInt(deleteId));

                //Publication doesn't exist
                if(publication==null)
                {
                    try {
                        httpServletResponse.sendRedirect("/bob-web/service/yok.htm");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    //Is your publication?
                    if(publication.getUserId().equals(getLoggedInUser(httpServletRequest).getUserId()))
                    {
                        publicationDao.deletePublication(Integer.parseInt(deleteId));

                        try {
                            httpServletResponse.sendRedirect("/bob-web/service/publications.htm");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        try {
                            httpServletResponse.sendRedirect("/bob-web/service/publications.htm");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return new ModelAndView("publications", "model", myModel);
            }

            return new ModelAndView("publications", "model", myModel);
        }
    }

    /**
     * Handles form submissions the page
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return page
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView handlePost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();

        String save = httpServletRequest.getParameter("save");

        int publicationId = Integer.parseInt(httpServletRequest.getParameter("publicationId"));

        if(null != save)
        {
            Publication publication;

            if(publicationId==-1)
            {
                publication=new Publication();
                publication.setUserId(getLoggedInUser(httpServletRequest).getUserId());
                publication.setAuthors(httpServletRequest.getParameter("authors"));
                publication.setTitle(httpServletRequest.getParameter("title"));
                publication.setLocation(httpServletRequest.getParameter("location"));
                publication.setDate(httpServletRequest.getParameter("date"));
                publication.setOtherInformation(httpServletRequest.getParameter("otherInformation"));

                publicationDao.save(publication);

                compositeDao.addUserFeed(getLoggedInUser(httpServletRequest).getUserId(), getLoggedInUser(httpServletRequest).getUserId(), "New publication: " + publication.getTitle());
                

                try
                {
                    httpServletResponse.sendRedirect("/bob-web/service/publications.htm");
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                publication=publicationDao.getPublicationByPublicationId(Integer.parseInt(httpServletRequest.getParameter("publicationId")));
                publication.setUserId(getLoggedInUser(httpServletRequest).getUserId());
                publication.setAuthors(httpServletRequest.getParameter("authors"));
                publication.setTitle(httpServletRequest.getParameter("title"));
                publication.setLocation(httpServletRequest.getParameter("location"));
                publication.setDate(httpServletRequest.getParameter("date"));
                publication.setOtherInformation(httpServletRequest.getParameter("otherInformation"));

                publicationDao.update(publication);

                try
                {
                    httpServletResponse.sendRedirect("/bob-web/service/publications.htm");
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

        }
        
        myModel.put("himself", true);
        return new ModelAndView("publications", "model", myModel);
    }
    private boolean isHeFriend(User loggedInUser, User wantedUser){
        for (Friend friend : loggedInUser.getFriends()) {
            if(wantedUser.getUserId().intValue() == friend.getUser2Id().intValue()) {
                return true;
            }
        }
        return false;
    }
    
}